import {
	pub,
	sub
} from '@/common/event.js'
import store from '@/store/index.js'
import moment from 'moment'
import {
	getRqst
} from '../../common/request'
import auth from '../../utils/auth'

export default {
	namespaced: true,
	state: {
		user: {},
		collect: []
	},
	mutations: {
		cleardata:(state, payload)=>{
			state.user = {}
			state.collect = []
		},
		setUserData: (state, payload) => {
			for (let k in payload) {
				state.user[k] = payload[k]
			}
			uni.setStorageSync("user", state.user)
		},
		setUser: (state, payload) => {
			state.user = payload
			uni.setStorageSync("user", payload)
		},
		setCollect: (state, payload) => {
			state.collect = payload.sort((a, b) => {
				return b.ctime - a.ctime
			})
		},
	},
	actions: {
		async init({
			commit,
			state
		}, {
			payload
		}) {
			const user = uni.getStorageSync("user")
			const ret = await getRqst().get(`bgyx/bgyx/getdata/user/${user.id}`)
			if (ret && ret.data) {
				commit(`setUser`, ret.data)
			}
		},
		async getUserCollect({
			commit,
			state
		}, {
			payload
		}) {
			const user = uni.getStorageSync("user")
			const ret = await getRqst().get(`chat/chat/getusercollect`)
			console.log(225588, ret)
			if (ret && ret.success && ret.data) {
				commit(`setCollect`, ret.data)
			}
		},
	},
	init: async function() {

		console.log("user初始化")
		const user = uni.getStorageSync("user")
		if (user && user.id) {
			store.dispatch({
				type: `user/init`,
				payload: {}
			})
			store.dispatch({
				type: `user/getUserCollect`,
				payload: {}
			})
		}
		sub("loginSuccess", function(e) {
			store.commit(`user/setUser`, e)
			store.dispatch({
				type: `user/getUserCollect`,
				payload: e
			})
		
		})
		
		sub("logout", function(e) {
			store.commit(`user/cleardata`, {})
		})

		sub("collect_done", function(e) {
			store.dispatch({
				type: `user/getUserCollect`,
				payload: e
			})
		})
		
		sub("socket_systemupdateuser", function(e) {
			store.commit(`user/setUserData`,e)
			if(e.id == store.state.user.user.id && (e.status == "封禁" || e.status == 4)){
				auth.removeAuthorization()
				pub("logout",{})
				return
			}
		})
		
		sub("socket_systemupdatefriend", function(e) {
			store.commit(`friend/setUserData`,e)
		})
		
		sub("socket_systemdeleteuser", function(e) {
			auth.removeAuthorization()
			pub("logout",{})
		})
		
		
	}
}